package listbyorder.access201_300.test224;

import java.util.LinkedList;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/8/23 14:31
 */
public class Solution1 {

    public int calculate(String s) {
        char[] cs = s.toCharArray();
        return dg(cs, 0)[0];
    }

    private int[] dg(char[] cs, int c) {
        LinkedList<String> q = new LinkedList<>();
        int[] bra = null;
        int pre = 0;
        // 如果遍历到到了右括号，结束
        while (c < cs.length && cs[c] != ')') {
            if (cs[c] == ' ') {
                c++;
                continue;
            }
            if (cs[c] >= '0' && cs[c] <= '9') {
                pre = pre * 10 + (cs[c++] - '0');
            } else if (cs[c] != '(') {
                // 加减号
                q.add(String.valueOf(pre));
                pre = 0;
                q.add(String.valueOf(cs[c++]));
            } else {
                bra = dg(cs, c + 1);
                pre = bra[0];
                c = bra[1] + 1;
            }
        }
        q.add(String.valueOf(pre));
        return new int[]{getNum(q), c};
    }

    private int getNum(LinkedList<String> q) {
        int res = 0;
        String cur = null;
        boolean add = true;
        int num = 0;
        while (!q.isEmpty()) {
            cur = q.pollFirst();
            if (cur.equals("+")) {
                add = true;
            } else if (cur.equals("-")) {
                add = false;
            } else {
                num = Integer.valueOf(cur);
                res += add ? num : -num;
            }
        }
        return res;
    }
}
